package com.example.mybleapp;

import android.annotation.SuppressLint;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

class FileOperation {
    private static FileOutputStream fileOutputStream = null;
    private static String filepath = null;
    void OpenFile(File parent) {
        try { //创建数据所在目录
            File dir = new File(parent, "Data");
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    return;
                }
            }
            @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMddHHmmss");// 设置时间格式
            Date date = new Date(System.currentTimeMillis());//获取当前时间
            String filename = simpleDateFormat.format(date) + ".txt";
            File file = new File(dir, filename); // 创建文件
            if (!file.exists()) {
                if (!file.createNewFile()) {
                    return;
                }
            }
            filepath = dir.getPath() +"/Data"+filename;
            fileOutputStream = new FileOutputStream(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void SaveFile(final String content) {
        try{
            fileOutputStream.write(content.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String CloseFile(){
        try{
            if(fileOutputStream != null){
                fileOutputStream.close();
                fileOutputStream = null;
                return filepath;
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
